export async function getProvinceBoundary(areaName: string) {
    const apiUrl = `https://restapi.amap.com/v3/config/district?keywords=${encodeURIComponent(areaName)}&subdistrict=1&extensions=all&key=15f921f471f73ffedb54b93d1cdb9773`;

    try {
        const response = await fetch(apiUrl);
        if (!response.ok) {
            throw new Error(`请求失败: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        if (!data.districts || data.districts.length === 0) {
            throw new Error(`未找到 ${areaName} 的边界数据`);
        }

        // 递归查找匹配的区域
        const findMatchingDistrict = (districts: any[]): any => {
            for (const district of districts) {
                if (district.name.includes(areaName)) {
                    return district;
                }
                if (district.districts) {
                    const found = findMatchingDistrict(district.districts);
                    if (found) return found;
                }
            }
            return null;
        };

        const matchedDistrict = findMatchingDistrict(data.districts);
        if (!matchedDistrict || !matchedDistrict.polyline) {
            throw new Error(`未找到 ${areaName} 的边界数据`);
        }

        // 解析 polyline 并转换成 GeoJSON
        const coordinates = matchedDistrict.polyline.split('|').map((polygon: string) => {
            const rings = polygon.split(';').map((point: string) => {
                const [lng, lat] = point.split(',').map(Number);
                return [lng, lat];
            });
            if (rings.length > 0 && !(rings[0][0] === rings[rings.length - 1][0] && rings[0][1] === rings[rings.length - 1][1])) {
                rings.push(rings[0]);
            }
            return [rings];
        });

        return {
            type: "FeatureCollection",
            features: [{
                type: "Feature",
                properties: { name: areaName },
                geometry: {
                    type: "MultiPolygon",
                    coordinates: coordinates
                }
            }]
        };
    } catch (error) {
        throw new Error(`获取 ${areaName} 边界数据失败: ${error instanceof Error ? error.message : String(error)}`);
    }
}
